package com.tuling.code.algorithm.loadbalance.simple;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 简单的轮训算法
 * 
 * @author javaw
 *
 */
public class RoundRobin implements LoadBlanceStragety {
	//当前轮训到的服务器节点index下标位置，默认初始化为0
	private static Integer pos = 0;

	@Override
	public String getServer(String src) {
		// 重建一个Map，避免服务器的上下线导致的并发问题
		Map<String,Integer> serverMap = new HashMap<>();
		serverMap.putAll(IpMap.serverWeightMap);
		
		//获取IP地址列表
		Set<String> keySet = serverMap.keySet();
		
		ArrayList<String> keyList = new ArrayList<>();
		keyList.addAll(keySet);
		
		String server = null;
		
		synchronized (pos) {
			if(pos >= keySet.size()){
				//下标大于server size ,重头轮训
				pos = 0;
			}
			server = keyList.get(pos);
			pos ++;
		}
		return server;
	}

}
